#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <unordered_map>
#include <sys/stat.h>

#include "../Log.hpp"

std::unordered_map<int, std::string> _status_mas = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

class Util
{
public:
    // 字符串分割函数
    static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *array)
    {
        size_t offset = 0;
        while (offset < src.size())
        {
            // 找到分隔符的首字符下标
            size_t pos = src.find(sep, offset);
            if (pos == std::string::npos)
            {
                // 如果没有找到，就把剩下的字符作为一个字串全部放入数组中
                std::string tail_str = src.substr(offset);
                array->push_back(tail_str);
            }
            // 字符串是空的，也就是有两个sep在一起的情况
            if (pos == offset)
            {
                offset = pos + sep.size();
                continue;
            }

            // 提取出来
            std::string tmp = src.substr(offset, pos - offset);
            array->push_back(tmp);
            offset = pos + sep.size();
        }
        return array->size();
    }

    // 读取文件所以内容，放到一个Buffer中
    static bool ReadFile(const std::string &filename, std::string *buf)
    {
        // 打开文件
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false)
        {
            ERR_LOG("open filename:%s fail", filename.c_str());
            return false;
        }
        // 将指针跳转到文件末尾
        ifs.seekg(0, ifs.end);
        // 计算当前指针位置相文件开头的偏移量-->算出文件大小
        size_t fsize = ifs.tellg();

        // 读取文件中的所有数据
        buf->resize(fsize);
        ifs.read(&((*buf)[0]), fsize);
        // 判断流状态是否良好
        if (ifs.good())
        {
            ERR_LOG("read filename:%s file fail", filename.c_str());
            return false;
        }
        // 关闭文件描述符
        ifs.close();
        return true;
    }

    // 向文件中写入数据
    static bool WriteFile(const std::string &filename, const std::string &buf)
    {
        // 打开文件
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (ofs.is_open())
        {
            ERR_LOG("open filename:%s fail", filename.c_str());
            return false;
        }

        size_t size = buf.size();
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good())
        {
            ERR_LOG("wirte filename:%s file fail", filename.c_str());
            return false;
        }
        // 关闭文件描述符
        ofs.close();
        return true;
    }

    // URL编码
    static std::string UrlEnCode(const std::string &url, bool convert_space_to_plus)
    {
        std::string res;
        // 遍历字符串
        for (auto &ch : url)
        {
            // . - _ ~ 以及数字不会被转码
            if (ch == '.' || ch == '-' || ch == '_' || ch == '~' || ch == isalnum(ch))
            {
                res += ch;
                continue;
                ;
            }
            // w3c标准中，空格字符转换为+
            if (ch == ' ' && convert_space_to_plus == true)
            {
                res += '+';
                continue;
            }
            // 剩下的正常处理为 %HH 格式
            char tmp[4] = {0};
            snprintf(tmp, 4, "%%%02X", ch);
            res += tmp;
        }
        return res;
    }

    static char HEXTOI(char ch)
    {
        if (ch >= '0' && ch <= '9')
            return ch - '0';
        else if (ch >= 'a' && ch <= 'z')
            return ch - 'a' + 10;
        else if (ch >= 'A' && ch <= 'Z')
            return ch - 'A' + 10;
    }
    // URL解码
    static std::string UrlDeCode(const std::string &url, bool convert_plus_to_space)
    {
        std::string res;
        for (size_t i = 0; i < url.size(); i++)
        {
            if (url[i] == '+' && convert_plus_to_space == true)
            {
                res += " ";
                continue;
            }
            // 编码：字符-->10进制数字-->16进制-->字符   解码： 字符-->16进制-->10进制数字-->字符
            if (url[i] == '%' && (i + 2) < url.size())
            {
                char c1 = HEXTOI(url[i + 1]);
                char c2 = HEXTOI(url[i + 2]);
                char ch = c1 * 16 + c2;
                res += ch;
                i += 2;
                continue;
            }
            res += url[i];
        }
        return res;
    }

    // 响应状态码的描述信息获取
    static std::string StatusDesc(int status)
    {
        auto it = _status_mas.find(status);
        if (it == _status_mas.end())
            return "UnKnow";
        return it->second;
    }

    // 根据文件后缀名称获取文件mime
    static std::string ExtMime(const std::string &filename)
    {
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos)
            return "application/octet-stream";

        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end())
            return "application/octet-stream";
        return it->second;
    }

    // 判断一个文件是不是一个目录文件
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是不是一个普通文件
    static bool IsRegular(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }

    // 请求资源的有效路径判断
    static bool ValidPath(const std::string &path)
    {
        int level = 0;
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        for (auto &dir : subdir)
        {
            if (dir == "..")
            {
                level--;
                if (level < 0)
                    return false;
                continue;
            }
            level++;
        }
        return true;
    }
};